package com.shanzmoo.platform.manage.api.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shanzmoo.base.bean.PageRespBase;
import com.shanzmoo.base.bean.SHttpResponse;
import com.shanzmoo.base.util.CollectionUtil;
import com.shanzmoo.base.util.RedisUtil;
import com.shanzmoo.db.module.member.domain.dto.CardConfigSaveDTO;
import com.shanzmoo.db.module.member.domain.dto.MemberCardConfigDTO;
import com.shanzmoo.db.module.member.domain.dto.MemberCardConfigDetailDTO;
import com.shanzmoo.db.module.member.domain.query.*;
import com.shanzmoo.db.module.member.domain.vo.*;
import com.shanzmoo.db.module.member.entity.*;
import com.shanzmoo.db.module.member.service.*;
import com.shanzmoo.db.module.merchant.entity.MerchantInfoEntity;
import com.shanzmoo.db.module.merchant.service.IMerchantInfoService;
import com.shanzmoo.db.util.RandomUtil;
import com.shanzmoo.platform.manage.api.util.SecurityUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class PlfMemberManage {

    @Autowired
    private IMemberInfoService memberInfoService;

    @Autowired
    private IMemberMerchantService memberMerchantService;

    @Autowired
    private IMemberAccountScoreRecordService memberAccountScoreRecordService;

    @Autowired
    private IMemberAccountRecordService memberAccountRecordService;

    @Autowired
    private IMerchantInfoService merchantInfoService;
    @Autowired
    private IMemberCardConfigService memberCardConfigService;
    @Autowired
    private IMemberCardConfigDetailService memberCardConfigDetailService;
    @Autowired
    private IMemberActivityConfigService activityConfigService;
    @Autowired
    private IMemberActivityConfigDetailService activityConfigDetailService;
    @Autowired
    private IMemberCouponConfigService memberCouponConfigService;
    @Autowired
    private ICardConfigService cardConfigService;
    /**
     * 分页查询会员总表
     * @param query
     * @return
     */
    public SHttpResponse<PageRespBase<MemberInfoVO>> getMemberListPage(MemberQuery query) {
        Page<MemberInfoVO> page = memberInfoService.queryByPage(query);
        PageRespBase<MemberInfoVO> re = PageRespBase.create(page);
        return SHttpResponse.ok(re);
    }

    /**
     * 平台会员详情
     * @param id
     * @return
     */
    public SHttpResponse<MemberInfoDetailVO> memberDetail(Integer id) {
        MemberInfoDetailVO memberInfoDetailVO = new MemberInfoDetailVO();
        memberInfoDetailVO.setId(id);

        List<MemberMerchantEntity> memberMerchantEntities = memberMerchantService.getByPlatformMemberId(id);


        if (cn.hutool.core.collection.CollectionUtil.isNotEmpty(memberMerchantEntities)){
            //会员基本信息
            memberInfoDetailVO.setMemberDetail(CollectionUtil.convert(memberMerchantEntities, MemberMerchantVO.class));

            //查询流水表中该用户的流水
            List<MemberAccountRecordEntity> recordList = memberAccountRecordService.getByMemberIds(memberMerchantEntities.stream().map(MemberMerchantEntity::getId).collect(Collectors.toList()));
            if (!CollectionUtils.isEmpty(recordList)) {
                //流水表没记录直接返回
                List<MemberAccountRecordEntity> rechargeList = recordList.stream().filter(a -> a.getType() == 1).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(rechargeList)) {
                    memberInfoDetailVO.setRechargeAmt(rechargeList.stream().mapToLong(MemberAccountRecordEntity::getAmount).sum());
                    memberInfoDetailVO.setRechargeCount(rechargeList.size());
                }
                List<MemberAccountRecordEntity> resumeList = recordList.stream().filter(a -> a.getType() == 2).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(resumeList)) {
                    memberInfoDetailVO.setResumeAmt(resumeList.stream().mapToLong(MemberAccountRecordEntity::getAmount).sum());
                    memberInfoDetailVO.setResumeCount(resumeList.size());
                }

            }
        }
        return SHttpResponse.ok(memberInfoDetailVO);
    }

    /**
     * 账户储值消费记录分页查询
     * @param query
     * @return
     */
    public SHttpResponse<PageRespBase<MemberAccountRecordVO>> accountList(MemberMerchantIdPageQuery query) {
        MemberAccountPageQuery query2 = new MemberAccountPageQuery();
        query2.setMemberInfoId(query.getId());
        IPage<MemberAccountRecordVO> memberAccountRecordVOIPage = memberAccountRecordService.queryByRequest(query2);
        PageRespBase<MemberAccountRecordVO> re = PageRespBase.create(memberAccountRecordVOIPage, memberAccountRecordVOIPage.getRecords());
        return SHttpResponse.ok(re);
    }

    /**
     *
     * @param id
     * @return
     */
    public SHttpResponse<MemberAccountRechargeDetailVO> rechargeDetail(Integer id) {
        MemberAccountRechargeDetailVO response = new MemberAccountRechargeDetailVO();
        MemberAccountRecordEntity memberAccountRecordEntity = memberAccountRecordService.getById(id);
        BeanUtils.copyProperties(memberAccountRecordEntity,response);
        if (!StringUtils.isEmpty(memberAccountRecordEntity.getOrderNo())){
            //todo 关联订单
        }
        return SHttpResponse.ok(response);
    }

    public SHttpResponse<MemberAccountConsumeDetailVO> consumeDetail(Integer id) {
        MemberAccountConsumeDetailVO response = new MemberAccountConsumeDetailVO();
        MemberAccountRecordEntity memberAccountRecordEntity = memberAccountRecordService.getById(id);
        BeanUtils.copyProperties(memberAccountRecordEntity,response);
        if (!StringUtils.isEmpty(memberAccountRecordEntity.getOrderNo())){
            //todo 关联订单
        }
        return SHttpResponse.ok(response);
    }

    /**
     * 活动列表
     * @param request
     * @return
     */
    public SHttpResponse<PageRespBase<MemberActivityConfigVO>> activityList(MemberActivityPageQuery request) {
        Page<MemberActivityConfigVO> page = activityConfigService.queryPlfByRequest(request);
        PageRespBase<MemberActivityConfigVO> re = PageRespBase.create(page);
        return SHttpResponse.ok(re);
    }

    /**
     * 活动详情
     * @param id
     * @return
     */
    public SHttpResponse<MemberActivityConfigVO> activityDetail(Integer id) {
        MemberActivityConfigVO response = new MemberActivityConfigVO();
        MemberActivityConfigEntity activityConfig = activityConfigService.getById(id);
        if (activityConfig != null){
            BeanUtils.copyProperties(activityConfig,response);
            List<MemberActivityConfigDetailEntity> activityConfigDetails =  activityConfigDetailService.getbyActivityConfigId(id);
            if (!CollectionUtil.isEmpty(activityConfigDetails)){
                List<MemberActivityConfigDetailVO> reList = CollectionUtil.convert(activityConfigDetails, MemberActivityConfigDetailVO.class);
                response.setActivityDetail(reList);
            }
        }

        return SHttpResponse.ok(response);
    }

    public SHttpResponse<PageRespBase<MemberAccountScoreRecordVO>> getMemberMerchantScoreList(MemberMerchantIdPageQuery request) {
        List<MemberMerchantEntity> memberMerchantEntities = memberMerchantService.getByPlatformMemberId(request.getId());
        if (CollectionUtil.isNotEmpty(memberMerchantEntities)){
            Page<MemberAccountScoreRecordEntity> page = memberAccountScoreRecordService.getbyMemberIds(request.page(),memberMerchantEntities.stream().map(MemberMerchantEntity::getId).collect(Collectors.toList()));
            List<MemberAccountScoreRecordVO> reList = CollectionUtil.convert(page.getRecords(), MemberAccountScoreRecordVO.class);
            PageRespBase<MemberAccountScoreRecordVO> re = PageRespBase.create(page,reList);
            return SHttpResponse.ok(re);
        }
        return SHttpResponse.ok(new PageRespBase<>());
    }

    public SHttpResponse<PageRespBase<MemberOpenVO>> getMemberOpenList(MemberMerchantIdPageQuery request) {
        Page<MemberOpenVO> page = memberInfoService.queryMemberMerchantByRequest(request);
        PageRespBase<MemberOpenVO> re = PageRespBase.create(page);
        return SHttpResponse.ok(re);
    }

    public SHttpResponse<PageRespBase<MemberAccountTransVO>> transList(MemberTransPageQuery request) {

        Page<MemberAccountTransVO> page = memberAccountRecordService.transListByRequest(request);
        PageRespBase<MemberAccountTransVO> re = PageRespBase.create(page);
        return SHttpResponse.ok(re);
    }

    public SHttpResponse<PageRespBase<PlfMemberCardConfigVO>> getCardList(PlfMemberCardConfigQuery query) {
        Page<PlfMemberCardConfigVO> page = memberCardConfigService.queryPlfByRequest(query);
        PageRespBase<PlfMemberCardConfigVO> re = PageRespBase.create(page);
        List<PlfMemberCardConfigVO> list = re.getList();

        for (PlfMemberCardConfigVO vo:list){
            Integer id = vo.getId();
            List<MemberCardConfigDetailEntity> memberCardConfigDetailEntities = memberCardConfigDetailService.getbyConfigId(id);
            if (!CollectionUtils.isEmpty(memberCardConfigDetailEntities) && memberCardConfigDetailEntities.size()>=3){
                vo.setDefaultAmtFirst(memberCardConfigDetailEntities.get(0).getDefaultAmt());
                vo.setGiveAmtFirst(memberCardConfigDetailEntities.get(0).getGiveAmt());
                vo.setDefaultAmtSecond(memberCardConfigDetailEntities.get(1).getDefaultAmt());
                vo.setGiveAmtSecond(memberCardConfigDetailEntities.get(1).getGiveAmt());
                vo.setDefaultAmtThird(memberCardConfigDetailEntities.get(2).getDefaultAmt());
                vo.setGiveAmtThird(memberCardConfigDetailEntities.get(2).getGiveAmt());
            }
        }

        return SHttpResponse.ok(re);
    }

    public SHttpResponse<MemberCardConfigDTO> cardConfigDetail(Integer id) {
        MemberCardConfigDTO memberCardConfigDTO = new MemberCardConfigDTO();
        MemberCardConfigEntity memberCardConfigEntity = memberCardConfigService.getById(id);
        if (memberCardConfigEntity!=null){
            memberCardConfigEntity.setPassword(null);
            BeanUtils.copyProperties(memberCardConfigEntity,memberCardConfigDTO);
            List<MemberCardConfigDetailEntity> details =memberCardConfigDetailService.getbyConfigId(memberCardConfigEntity.getId());
            if (!CollectionUtils.isEmpty(details)){
                List<MemberCardConfigDetailDTO> collect = details.stream().map(a -> {
                    MemberCardConfigDetailDTO detailDTO = new MemberCardConfigDetailDTO();
                    detailDTO.setCardConfigId(a.getCardConfigId());
                    detailDTO.setDefaultAmt(a.getDefaultAmt());
                    detailDTO.setGiveAmt(a.getGiveAmt());
                    return detailDTO;
                }).collect(Collectors.toList());
                memberCardConfigDTO.setCardConfigDetail(collect);
            }
        }
        return SHttpResponse.ok(memberCardConfigDTO);
    }

    public SHttpResponse<PageRespBase<MemberCouponConfigVO>> getCouponList(MemberCouponConfigPageQuery request) {
        Page<MemberCouponConfigVO> page = memberCouponConfigService.getPlfByRequest(request);
        PageRespBase<MemberCouponConfigVO> re = PageRespBase.create(page);
        return SHttpResponse.ok(re);
    }

    public SHttpResponse<MemberCouponConfigVO> getCouponDetail(Integer id) {
        MemberCouponConfigEntity memberCouponConfigEntity = memberCouponConfigService.getById(id);
        MemberCouponConfigVO res = new MemberCouponConfigVO();
        BeanUtils.copyProperties(memberCouponConfigEntity,res);
        return SHttpResponse.ok(res);
    }

    /**
     * 平台会员卡管理 保存
     * @param request
     * @return
     */
    public SHttpResponse<Boolean> saveCardConfig(CardConfigSaveDTO request) {
        List<CardConfigEntity> list = cardConfigService.list();
        if (CollectionUtil.isNotEmpty(list)){
            List<Integer> collect = list.stream().map(CardConfigEntity::getId).collect(Collectors.toList());
            cardConfigService.removeByIds(collect);
        }
        CardConfigEntity cardConfigEntity = new CardConfigEntity();
        BeanUtils.copyProperties(request,cardConfigEntity);
        cardConfigEntity.setCreateTime(LocalDateTime.now());
        cardConfigEntity.setUpdateTime(LocalDateTime.now());
        cardConfigEntity.setCreateUser(SecurityUtil.getCurrentUserId());
        cardConfigService.save(cardConfigEntity);
        return SHttpResponse.ok(true);
    }

    /**
     * 平台会员管理 详情
     * @return
     */
    public SHttpResponse<CardConfigDetailVO> getCardConfigDetail() {
        CardConfigDetailVO response = new CardConfigDetailVO();
        List<CardConfigEntity> list = cardConfigService.list();
        if (CollectionUtil.isNotEmpty(list)){
            CardConfigEntity cardConfigEntity = list.get(0);
            BeanUtils.copyProperties(cardConfigEntity,response);
            return SHttpResponse.ok(response);
        }
        return SHttpResponse.ok(response);
    }

    public SHttpResponse<Boolean> sendSmsMsg() {
        /*Integer currentUserId = SecurityUtil.getCurrentUserId();

        MerchantInfoEntity merchantInfoEntity = merchantInfoService.getByMerchantCode(merchantCode);
        if (merchantInfoEntity == null){
            return SHttpResponse.fail(33211,"商户配置不存在");
        }
        String mobile = merchantInfoEntity.getMobile();
        if (StringUtils.isEmpty(mobile)){
            return SHttpResponse.fail(33211,"商户手机号未配置");
        }
        // 1、构建验证码信息并存入缓存
        String code = RandomUtil.createRandom(false, 6);
        // 2、存入缓存(10分钟有效)
        RedisUtil.set("PLF_MEMBER_CARD_CONFIG_"+currentUserId, code, 10l);
        // 3、发送验证短信
        aliSmsManager.sendLoginSms(mobile, code);*/
        return SHttpResponse.ok();
    }
}
